<template>
  <div class="orgInfo-container">
    <div class="header-title">科室信息</div>
    <el-divider></el-divider>
    <el-form ref="formRef" :rules="rules" :model="form" label-width="80px">
      <el-form-item label="科室名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入医院名称"></el-input>
      </el-form-item>
      <!-- <el-form-item label="备注">
        <el-input v-model="form.region" placeholder="请选择地区"></el-input>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="goBack">返回上一页</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import { reactive } from '@vue/reactivity'
  import { ref } from '@vue/reactivity'
  import { useRouter } from 'vue-router'
  import { departmentInfo, save } from '@/api/modules/departments'
  import { useRoute } from 'vue-router'
  import { onBeforeMount } from '@vue/runtime-core'
  import { ElMessage } from 'element-plus'
  export default {
    setup() {
      const route = useRoute()
      const router = useRouter()
      const formRef = ref(null)
      const form = reactive({
        name: '',
      })

      const rules = {
        name: [
          { required: true, message: '请输入科室名称', trigger: 'blur' },
          { min: 0, max: 100, message: '最多100个字符', trigger: 'blur' },
        ],
      }

      let id = ref(null)
      onBeforeMount(() => {
        if (route.query.id) {
          id.value = route.query.id
          loadData(id.value)
        }
      })

      // 事件处理
      const loadData = async function (id) {
        const res = await departmentInfo({ id })
        if (res.data.name) form.name = res.data.name
      }
      const toSave = async function (name, id) {
        await save({ name, id })
        goBack()
      }
      const goBack = function () {
        router.go(-1)
      }
      const onSubmit = function () {
        console.log('form =' + JSON.stringify(form))
        formRef.value.validate((valid) => {
          if (valid) {
            console.log(
              'form =' + JSON.stringify(form) + ' id.value = ' + id.value
            )
            toSave(form.name, id.value)
            ElMessage.success('提交成功！')
          } else {
            return false
          }
        })
      }
      return {
        form,
        goBack,
        rules,
        onSubmit,
        formRef,
      }
    },
  }
</script>
<style lang="scss" scoped>
  .orgInfo-container {
    margin: 32px;
    background-color: white;
    overflow: hidden;
    .header-title {
      margin-top: 20px;
      margin-left: 11px;
    }
    .el-form {
      width: 50%;

      .el-select {
        width: 100%;
      }

      .el-input {
        width: 100% !important;
      }
    }
  }
</style>
